<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\RabbitMQClient;
use think\facade\Db;
use think\Request;
use think\facade\Log;

class Test
{
    /**
     * @describe
     * @author: Bobo
     * @date: 2024-11-25 11:03:35
     * @param [type] @required
     * @return Renderable
     */
    public function sendMessage()
    {

        $rabbitMQService = new RabbitMQClient();
        try {
            $queueName = 'yiduiduo';
            for ($i = 0; $i < 4; $i++) {
                $message = json_encode($i);
                $rabbitMQService->sendMessage($queueName, $message);
            }
        } catch (\Exception $e) {
            echo "Failed to send delayed message: " . $e->getMessage() . "\n";
        } finally {
            $rabbitMQService->close();
        }
    }

    public function receiveMessage()
    {
        $rabbitMQService = new RabbitMQClient();
        try {
            // 监听死信队列并处理消息
            $rabbitMQService->receiveMessage('yiduiduo', function ($message) {
                // 这里写业务代码。返回 trur 表示消费成功，返回 false 表示消费失败，消息会重新放回队列
                if ($message % 2 == 0) {
                    echo "Processing message: $message\n";
                    return true;
                } else {
                    return false;
                }
            });
        } catch (\Exception $e) {
            echo "Failed to consume messages: " . $e->getMessage() . "\n";
        }
    }

    public function sendDelayedMessage()
    {

        echo '<pre>';
        echo 'starttttttttttttttttt';
        echo PHP_EOL;
        print_r(config()['database']);
        echo PHP_EOL;
        echo 'enddddddddddddddddddd';
        exit();
        $rabbitMQService = new RabbitMQClient();
        try {
            $delaySecondsA = 3; // 延迟 5 秒
            $queueNameA = 'ordinaryQueueOrderCreate_' . $delaySecondsA; // 普通队列名称 订单创建审核
            $messageA = json_encode([
                'id' => 571,
                'order_type' => 'order',
                'queue_type' => 1 // 1:创建，审核订单 2:上传支付凭证
            ]);
            $result1 = $rabbitMQService->sendDelayedMessage($queueNameA, $delaySecondsA, $messageA);

            // $delaySecondsB = 9; // 延迟 5 秒
            // $queueNameB = 'OrdinaryQueueUploadVoucherPayment' . '_' . $delaySecondsB;  // 普通队列名称 上传凭证支付
            // $messageB = json_encode(['time' => date('Y-m-d H:i:s'), 'type' => 2, 'content' => 'This is a OrdinaryQueueUploadVoucherPayment delayed message']);


            // $result2 = $rabbitMQService->sendDelayedMessage($queueNameB, $delaySecondsB, $messageB);

            if ($result1) {
                echo "Delayed message sent successfully.\n";
            } else {
                echo "Failed to send delayed message.\n";
            }
        } catch (\Exception $e) {
            echo "Failed to send delayed message: " . $e->getMessage() . "\n";
        } finally {
            $rabbitMQService->close();
        }
    }

    public function receiveDelayMessage()
    {
        $rabbitMQService = new RabbitMQClient();
        try {
            // 监听死信队列并处理消息
            $rabbitMQService->receiveDelayedMessage('shifangkucu_2', function ($message) {
                // 模拟业务逻辑处理
                if (time() % 2 == 0) {
                    echo  time() . "Processing message: $message\n";
                    return true;
                } else {
                    return false;
                }
            });
        } catch (\Exception $e) {
            // 记录日志或处理异常
            return false;
        }
    }

    public function simulatLockedInventory()
    {
        // 查询模拟商品列表
        $list = Db::name('inventory')
            ->field('productid,wid,arrival_date,is_futures,sum(available_qty) as available_qty, sum(lock_qty) as lock_qty')
            ->where([
                'is_del' => 0,
                'is_sale' => 1,
                ['available_qty', '>', 0],
                ['productid', 'in', '22']
            ])
            ->group('productid,wid,arrival_date,is_futures')
            ->select()
            ->toArray();

        $processedList = [];
        foreach ($list as $item) {
            $wids = explode(',', $item['wid']);
            foreach ($wids as $wid) {
                $newItem = $item;
                $newItem['wid'] = $wid;

                // 合并相同 productid 和 wid 的数据（如果有）
                $existingKey = null;
                foreach ($processedList as $key => $processedItem) {
                    if (
                        $processedItem['productid'] == $newItem['productid'] &&
                        $processedItem['wid'] == $newItem['wid']
                    ) {
                        $existingKey = $key;
                        break;
                    }
                }

                if ($existingKey !== null) {
                    $processedList[$existingKey]['available_qty'] += $newItem['available_qty'];
                } else {
                    $processedList[] = $newItem;
                }
            }
        }

        // 模拟购买列表
        $buyList = [
            [
                'productid' => 22,
                'wid' => 7,
                'num' => 1200,
                'arrival_date' => '2024-10-29',
                'is_futures' => 2,
            ],
            [
                'productid' => 22,
                'wid' => 7,
                'num' => 1200,
                'arrival_date' => '2024-10-23',
                'is_futures' => 2,
            ]
        ];

        // 开始库存锁定的部分，需要使用锁和事务
        Db::startTrans();
        try {
            foreach ($buyList as $buyItem) {
                $buynum = $buyItem['num'];

                // 查询具体库存记录，并加锁
                $inventoryList = Db::name('inventory')
                    ->field('id,productid,wid,arrival_date,is_futures,available_qty,lock_qty')
                    ->whereFindInSet('wid', $buyItem['wid'])
                    ->where([
                        'is_del' => 0,
                        'is_sale' => 1,
                        'productid' => $buyItem['productid'],
                        'arrival_date' => $buyItem['arrival_date'],
                        ['available_qty', '>', 0],
                    ])
                    ->lock(true) // 使用行级锁，防止并发修改
                    ->select();

                foreach ($inventoryList as $key => $inventory) {
                    if ($buynum <= 0) {
                        break;
                    }
                    $keyongkucun = $inventory['available_qty'] - $inventory['lock_qty'];
                    if ($buynum <= $keyongkucun) {
                        $lockQty = $buynum;
                        $buynum = 0;
                    } else {
                        $lockQty = $keyongkucun;
                        $buynum -= $keyongkucun;
                    }




                    // 更新锁定库存
                    Db::name('inventory')
                        ->where('id', $inventory['id'])
                        ->inc('lock_qty', $lockQty)
                        ->update();
                }

                // 如果最终的 buynum 不为 0，则说明库存不足，回滚事务
                if ($buynum > 0) {
                    throw new \Exception('库存不足，无法完成购买');
                }
            }

            // 提交事务
            Db::commit();

            // 返回数据
            return json($buyList);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();

            // 返回错误信息
            return json(['error' => $e->getMessage()]);
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-01 16:54:55 
     * @param [type] @required
     * @return Renderable
     */
    public function Test()
    {


        $list = Db::table('ip2region')
            ->where('c1', '=', '0')
            ->field('region_name')
            ->group('region_name')
            ->select()
            ->toArray();
        $count1 = count($list) - 1;
        $count2 = 0;
        $count3 = 0;
        $list2 = [];
        $list3 = [];
        foreach ($list as $item) {
            $region_name = $item['region_name'];
            if (0 != $region_name) {
                $res = Db::table('db_region_country')
                    ->where('cname', 'like', '%' . $region_name . '%')
                    ->field('id,full_name')
                    ->find();

                if ($res) {
                    $id = $res['id'];
                    $full_name = $res['full_name'];
                    $list2[] = [
                        'id' => $id,
                        'region_name' => $region_name,
                        'full_name' => $full_name
                    ];
                    $count2++;
                } else {
                    $count3++;
                    $list3[] = [
                        'region_name' => $region_name
                    ];
                }
            }
        }
        // 输出list2到文件
        $list2_content = '';
        foreach ($list2 as $item) {
            $list2_content .= "ID: {$item['id']}, 地区: {$item['region_name']}, 全名: {$item['full_name']}\n";
        }
        $res = file_put_contents('./matched_regions.txt', $list2_content);
        if ($res) {
            echo 'matched_regions.txt 写入成功';
        } else {
            echo 'matched_regions.txt 写入失败';
        }

        // 输出list3到文件
        $list3_content = '';
        foreach ($list3 as $item) {
            $list3_content .= "地区: {$item['region_name']}\n";
        }
        file_put_contents('./unmatched_regions.txt', $list3_content);
        echo '<pre>';
        echo 'starttttttttttttttttt';
        echo PHP_EOL;
        echo 'count1:' . $count1;
        echo PHP_EOL;
        echo 'count2:' . $count2;
        echo PHP_EOL;
        // print_r($list2);
        echo PHP_EOL;
        echo 'enddddddddddddddddddd';
        exit();
    }
}
